import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout'

// 权限拦截 导航守卫 路由守卫  router
// import router from '@/router' // 引入路由实例
import store from '@/store' // 引入vuex store实例
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式
import getPageTitle from '@/utils/get-page-title'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Layout',
    redirect: '',
    component: Layout,
    children: [
      {
        path: '',
        name: 'List',
        component: () => import('@/views/list'),
        hidden: true,
        meta: { title: '文章列表' }
      },
      {
        path: 'details/:article_id',
        name: 'Details',
        component: () => import('@/views/details'),
        hidden: true,
        meta: { title: '文章详情' }
      },
      {
        path: 'user/settings',
        name: 'UserSettings',
        component: () => import('@/views/Settings'),
        hidden: true,
        meta: { title: '设置中心', isLogin: true }
      },
      {
        path: 'user/:user_id',
        name: 'User',
        component: () => import('@/views/User'),
        hidden: true,
        meta: { title: '个人中心', isLogin: true }
      },
      {
        path: 'creator',
        name: 'Creator',
        redirect: '/creator/home',
        component: () => import('@/views/Creator'),
        hidden: true,
        meta: { title: '创作者中心', isLogin: true },
        children: [
          {
            path: 'home',
            component: () => import('@/views/Creator/Home'),
            hidden: true,
            meta: { title: '首页', isLogin: true }
          },
          {
            path: '/creator/help/question',
            // path: 'help/question',
            component: () => import('@/views/Creator/Help'),
            hidden: true,
            meta: { title: '常见问题', isLogin: true }
          },
          {
            path: 'article',
            component: () => import('@/views/Creator/Article'),
            hidden: true,
            meta: { title: '内容管理', isLogin: true }
          }
        ]
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由的前置守卫
router.beforeEach(async function (to, from, next) {
  NProgress.start() // 开启进度条
  document.title = getPageTitle(to.meta.title)
  if (store.getters.token) {
    next() // 直接放行
  } else {
    if (to.meta.isLogin) {
      Message('请您先登录后再操作！')
      next('/') // 如果在黑名单上跳到首页
    } else {
      return next()
    }
  }
  NProgress.done() // 手动强制关闭一次  为了解决 手动切换地址时  进度条的不关闭的问题
})
// 后置守卫
router.afterEach(function () {
  NProgress.done() // 关闭进度条
})
export default router
